package com.liu.shrio02.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {

    /**
     * 核心三大对象
     *
     * Subject
     * SecurityManage
     * Realm
     *
     * @param model
     * @return
     */

    @RequestMapping(value = {"/index","/"})
    public String myMapping(Model model){
        model.addAttribute("msg","数据信息");
        return "index";
    }

    @RequestMapping(value = {"/user/add"})
    public String addMapping(){
        return "user/add";
    }


    @RequestMapping(value = {"/user/update"})
    public String updateMapping(){
        return "user/update";
    }

    @RequestMapping(value = {"/user/delete"})
    public String DeleteMapping(){

        return "user/delete";

    }

    @RequestMapping(value = {"/toLogin"})
    public String toLogin(){
        return "login/login";
    }

    @PostMapping("/login")
    public String login(String username,String password){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);  //执行登录

            return "index";
        } catch (UnknownAccountException uae) {
            System.out.println("用户名不存在 " + token.getPrincipal());
            return "login/login";
        } catch (IncorrectCredentialsException ice) {
            System.out.println("密码错误 " + token.getPrincipal() + " was incorrect!");
            return "login/login";
        } catch (LockedAccountException lae) {
            System.out.println("用户锁定 " + token.getPrincipal() + " is locked.  " +
                    "Please contact your administrator to unlock it.");
            return "login/login";
        }
    }
    //未授权
    @RequestMapping(value = {"/user/noauth"})
    public String deleteMapping(){
        return "login/noauth";
    }

    @RequestMapping(value = {"/logout"})
    public String logout(){

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "index";
    }
}
